package com.example.idachuappone.cook.item;

import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import antistatic.spinnerwheel.OnWheelChangedListener;
import antistatic.spinnerwheel.OnWheelScrollListener;
import antistatic.spinnerwheel.WheelView;
import antistatic.spinnerwheel.adapters.AbstractWheelTextAdapter;
import antistatic.spinnerwheel.adapters.ArrayWheelAdapter;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.cook.action.CookAction;
import com.example.idachuappone.cook.entity.CookResult;
import com.example.idachuappone.index.dialog.DialogPackage;
import com.example.idachuappone.index.dialog.DialogPackage.CallBack;
import com.example.idachuappone.index.welcomentity.Packages;
import com.example.idachuappone.person.entity.Order;
import com.example.idachuappone.person.item.LoginActivity;
import com.example.idachuappone.promptly.entity.Addresses;
import com.example.idachuappone.promptly.item.CookAddressListActivity;
import com.example.idachuappone.utils.BitmapUtilHelper;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.example.idachuappone.utils.Utils;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class CookPromptlyActivity extends BaseActivity implements OnCheckedChangeListener, OnClickListener {
	private int addressRequestCode;
	private Addresses addresses;
	private Button btn_back;
	private TextView btn_ok;
	private Button btn_submit;
	private BitmapUtils bu;
	private CookAction cookAction;
	private CookResult cookResult;
	private CusProSmallBgDialog cusProDialog;
	WheelView date;
	private String detailTimeFormat;
	private Dialog dialogPackages;
	private EditText et_desc;
	WheelView hours;
	private ImageView img_cook_head;
	private int ingredient;
	private boolean isNoAddress;
	private LinearLayout ll_address;
	private LinearLayout ll_address_gone;
	private LinearLayout ll_address_visible;
	private LinearLayout ll_package;
	private LinearLayout ll_package_gone;
	private LinearLayout ll_package_visible;
	private LinearLayout ll_time;
	private LinearLayout ll_time_gone;
	private LinearLayout ll_time_visible;
	private int loginRequest;
	private int[] mActiveCities;
	private int mActiveCountry;
	private Packages packagesub;
	private RadioGroup rg_isfood;
	private boolean scrolling;
	private Dialog timeDialog;
	private TextView tv_day;
	private TextView tv_desc;
	private TextView tv_hour_min;
	private TextView tv_name;
	private TextView tv_packages;
	private TextView tv_service_for;
	private TextView tv_tags_greed;
	private TextView tv_user_address;
	private TextView tv_user_name;
	private TextView tv_user_phone;
	private TextView tv_year_mon_day;

	class AnonymousClass_7 implements OnWheelChangedListener {
		private final/* synthetic */String[][] val$cities;

		AnonymousClass_7(String[][] strArr) {
			this.val$cities = strArr;
		}

		@Override
		public void onChanged(WheelView wheel, int oldValue, int newValue) {
			if (!CookPromptlyActivity.this.scrolling) {
				CookPromptlyActivity.this.updateCities(CookPromptlyActivity.this.hours, this.val$cities, newValue);
			}
		}
	}

	class AnonymousClass_8 implements OnWheelScrollListener {
		private final/* synthetic */String[][] val$cities;

		AnonymousClass_8(String[][] strArr) {
			this.val$cities = strArr;
		}

		@Override
		public void onScrollingStarted(WheelView wheel) {
			CookPromptlyActivity.this.scrolling = true;
		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			CookPromptlyActivity.this.scrolling = false;
			CookPromptlyActivity.this.updateCities(CookPromptlyActivity.this.hours, this.val$cities,
					CookPromptlyActivity.this.date.getCurrentItem());
		}
	}

	private class CountryAdapter extends AbstractWheelTextAdapter {
		protected CountryAdapter(Context context) {
			super(context, 2130903109, 0);
			setTextTypeface(Typeface.DEFAULT);
			setItemTextResource(R.id.date_ymd);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			return super.getItem(index, cachedView, parent);
		}

		@Override
		public int getItemsCount() {
			return CookPromptlyActivity.this.cookResult.getWork_day() == null ? 0
					: CookPromptlyActivity.this.cookResult.getWork_day().size();
		}

		@Override
		protected CharSequence getItemText(int index) {
			return CookPromptlyActivity.this.cookResult.getWork_day() == null ? null
					: CookPromptlyActivity.this.cookResult.getWork_day().get(index).getDate();
		}
	}

	public CookPromptlyActivity() {
		this.ingredient = 0;
		this.addressRequestCode = 15;
		this.loginRequest = 255;
		this.scrolling = false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cook_promptly_two);
		this.cookAction = new CookAction();
		this.cusProDialog = new CusProSmallBgDialog(this);
		this.bu = BitmapUtilHelper.createBitmapUtil(this);
		this.cookResult = (CookResult) getIntent().getExtras().getSerializable("cookDetail");
		this.mActiveCities = new int[this.cookResult.getWork_day().size()];
		for (int i = 0; i < this.mActiveCities.length; i++) {
			this.mActiveCities[i] = 0;
		}
		this.timeDialog = showTime();
		showPackageDialog(this.cookResult.getPackages());
		initView();
		initData();
	}

	private void initData() {
		int length = BitmapCacheManagementTask.MESSAGE_FLUSH;
		this.tv_name.setText(this.cookResult.getName());
		this.tv_service_for.setText(this.cookResult.getService_for());
		if (this.cookResult.getTags() == null || this.cookResult.getTags().size() <= 0) {
			this.tv_tags_greed.setText("\u64c5\u957f\u5bb6\u5e38\u83dc");
		} else {
			String tag = "";
			if (this.cookResult.getTags().size() < 2) {
				length = this.cookResult.getTags().size();
			}
			for (int i = 0; i < length; i++) {
				tag = new StringBuilder(String.valueOf(tag)).append(this.cookResult.getTags().get(i).getName())
						.append("   ").toString();
			}
			this.tv_tags_greed.setText("\u64c5\u957f" + tag);
		}
		this.bu.display(this.img_cook_head, this.cookResult.getHead_small(), new BitmapLoadCallBack<View>() {
			@Override
			public void onLoadCompleted(View view, String arg1, Bitmap bitmap, BitmapDisplayConfig arg3,
					BitmapLoadFrom arg4) {
				((ImageView) view).setImageBitmap(BitmapUtilHelper.getCroppedRoundBitmap(bitmap,
						Utils.dip2px(CookPromptlyActivity.this, 25.0f)));
			}

			@Override
			public void onLoadFailed(View arg0, String arg1, Drawable arg2) {
			}
		});
	}

	private void initView() {
		this.rg_isfood = (RadioGroup) findViewById(R.id.rg_isfood);
		this.rg_isfood.setOnCheckedChangeListener(this);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.btn_submit = (Button) findViewById(R.id.btn_submit);
		this.btn_submit.setOnClickListener(this);
		this.tv_service_for = (TextView) findViewById(R.id.tv_service_for);
		this.tv_tags_greed = (TextView) findViewById(R.id.tv_tags_greed);
		this.ll_address = (LinearLayout) findViewById(R.id.ll_address);
		this.ll_address.setOnClickListener(this);
		this.ll_address_gone = (LinearLayout) findViewById(R.id.ll_address_gone);
		this.ll_address_visible = (LinearLayout) findViewById(R.id.ll_address_visible);
		this.tv_user_name = (TextView) findViewById(R.id.tv_user_name);
		this.tv_user_phone = (TextView) findViewById(R.id.tv_user_phone);
		this.tv_user_address = (TextView) findViewById(R.id.tv_user_address);
		initAddress();
		this.ll_package = (LinearLayout) findViewById(R.id.ll_package);
		this.ll_package.setOnClickListener(this);
		this.ll_package_gone = (LinearLayout) findViewById(R.id.ll_package_gone);
		this.ll_package_visible = (LinearLayout) findViewById(R.id.ll_package_visible);
		this.tv_packages = (TextView) findViewById(R.id.tv_packages);
		this.ll_time = (LinearLayout) findViewById(R.id.ll_time);
		this.ll_time.setOnClickListener(this);
		this.ll_time_gone = (LinearLayout) findViewById(R.id.ll_time_gone);
		this.ll_time_visible = (LinearLayout) findViewById(R.id.ll_time_visible);
		this.tv_day = (TextView) findViewById(R.id.tv_day);
		this.tv_year_mon_day = (TextView) findViewById(R.id.tv_year_mon_day);
		this.tv_hour_min = (TextView) findViewById(R.id.tv_hour_min);
		this.tv_packages = (TextView) findViewById(R.id.tv_packages);
		this.ll_time = (LinearLayout) findViewById(R.id.ll_time);
		this.ll_time.setOnClickListener(this);
		this.img_cook_head = (ImageView) findViewById(R.id.img_cook_head);
		this.tv_name = (TextView) findViewById(R.id.tv_name);
		this.ll_package = (LinearLayout) findViewById(R.id.ll_package);
		this.ll_package.setOnClickListener(this);
		this.btn_submit = (Button) findViewById(R.id.btn_submit);
		this.btn_submit.setOnClickListener(this);
		this.tv_desc = (TextView) findViewById(R.id.tv_desc);
		this.et_desc = (EditText) findViewById(R.id.et_desc);
		this.et_desc.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					CookPromptlyActivity.this.tv_desc
							.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				}
			}
		});
		this.et_desc.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (CookPromptlyActivity.this.et_desc.getText().toString().length() >= 100) {
					MainToast.show(CookPromptlyActivity.this, "\u5907\u6ce8\u6700\u591a\u53ef\u8f93\u5165100\u5b57", 0);
				}
			}
		});
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.rbtn_false /* 2131165279 */:
			this.ingredient = 1;
		case R.id.rbtn_true /* 2131165280 */:
			this.ingredient = 0;
		default:
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (this.isNoAddress) {
			initAddress();
		}
	}

	private void initAddress() {
		PrefUtil pp = PrefUtil.getInstance(this);
		if (pp.getXiaoQu() == null || pp.getXiaoQu().length() <= 0) {
			this.isNoAddress = true;
			this.ll_address_gone.setVisibility(0);
			this.ll_address_visible.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			return;
		}
		this.isNoAddress = false;
		this.ll_address_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
		this.ll_address_visible.setVisibility(0);
		this.addresses = new Addresses(pp.getUserAddressId(), "", pp.getName(), pp.getPhone(), pp.getArea(),
				pp.getXiaoQu(), pp.getDoor(), "", "");
		setAddress(this.addresses);
	}

	private void setAddress(Addresses addresses) {
		this.tv_user_name.setText(addresses.getName());
		this.tv_user_phone.setText(addresses.getPhone());
		this.tv_user_address.setText(addresses.getCommunity() + addresses.getDoor_number());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			finish();
		case R.id.ll_address /* 2131165259 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), this.loginRequest);
				return;
			}
			Intent intent = new Intent(this, CookAddressListActivity.class);
			if (this.addresses != null) {
				intent.putExtra("userAddressId", this.addresses.getId());
			}
			startActivityForResult(intent, this.addressRequestCode);
		case R.id.ll_time /* 2131165265 */:
			this.timeDialog.show();
		case R.id.ll_package /* 2131165271 */:
			this.dialogPackages.show();
		case R.id.btn_submit /* 2131165282 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), this.loginRequest);
			} else if (this.addresses == null) {
				MainToast.show(this, "\u8bf7\u60a8\u5b8c\u5584\u5730\u5740\u4fe1\u606f", 0);
			} else if (this.detailTimeFormat == null || this.detailTimeFormat.trim().length() <= 0) {
				MainToast.show(this, "\u8bf7\u60a8\u9009\u62e9\u65f6\u95f4", 0);
			} else if (this.packagesub == null) {
				MainToast.show(this, "\u8bf7\u60a8\u5b8c\u5584\u5957\u9910\u4fe1\u606f", 0);
			} else {
				this.btn_submit.setEnabled(false);
				Map<String, String> map = new HashMap();
				map.put("date", this.detailTimeFormat);
				map.put("package",
						new StringBuilder(String.valueOf(this.packagesub.getId())).append("-")
								.append(this.packagesub.getPrice()).toString());
				map.put("area", this.addresses.getArea());
				map.put("community", this.addresses.getCommunity());
				map.put("door_number", this.addresses.getDoor_number());
				map.put("name", this.addresses.getName());
				map.put("kitchener_id", this.cookResult.getId());
				map.put("phone", this.addresses.getPhone());
				map.put("ver", "2");
				map.put("memo", this.et_desc.getText().toString());
				map.put("ingredient", new StringBuilder(String.valueOf(this.ingredient)).toString());
				map.put("app", "2");
				NetUtil.post(this, Constant.PROMPTLY, map, new RequestCallBack<String>() {
					@Override
					public void onStart() {
						super.onStart();
						CookPromptlyActivity.this.cusProDialog.setMsg("\u63d0\u4ea4\u8ba2\u5355\u4e2d...");
						CookPromptlyActivity.this.cusProDialog.show();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						CookPromptlyActivity.this.cusProDialog.dismiss();
						try {
							JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
							if (jsonObject.getInt("code") == 10000) {
								Intent intent = new Intent(CookPromptlyActivity.this, PayPromptlyActivity.class);
								intent.putExtra("isprom", false);
								intent.putExtra("isorder", false);
								intent.putExtra("orderid", new Order().parseJson(jsonObject.getJSONObject("data"))
										.getId());
								CookPromptlyActivity.this.startActivity(intent);
								return;
							}
							MainToast.show(CookPromptlyActivity.this, jsonObject.getString("error"), 0);
							CookPromptlyActivity.this.btn_submit.setEnabled(true);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						CookPromptlyActivity.this.btn_submit.setEnabled(true);
						CookPromptlyActivity.this.cusProDialog.dismiss();
						MainToast.show(CookPromptlyActivity.this,
								CookPromptlyActivity.this.getResources().getString(R.string.netFail), 0);
					}
				});
			}
		case R.id.btn_ok /* 2131165342 */:
			this.tv_year_mon_day.setText(this.cookResult.getWork_day().get(this.date.getCurrentItem()).getDate());
			this.tv_hour_min.setText(new StringBuilder(String.valueOf(this.cookResult.getWork_day()
					.get(this.date.getCurrentItem()).getHh()[this.hours.getCurrentItem()])).append(":00").toString());
			this.detailTimeFormat = new StringBuilder(String.valueOf(this.cookResult.getWork_day()
					.get(this.date.getCurrentItem()).getDate()))
					.append(" ")
					.append(this.cookResult.getWork_day().get(this.date.getCurrentItem()).getHh()[this.hours
							.getCurrentItem()]).append(":00").toString();
			this.ll_time_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			this.ll_time_visible.setVisibility(0);
			String day = this.cookAction.getTimeDay(this.cookResult.getWork_day().get(this.date.getCurrentItem())
					.getDate());
			if (day == null || day.length() <= 0) {
				this.tv_day.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			} else {
				this.tv_day.setVisibility(0);
				this.tv_day.setText(day);
			}
			this.timeDialog.dismiss();
		default:
		}
	}

	private void showPackageDialog(List<Packages> packages) {
		this.dialogPackages = new DialogPackage(packages, this).showPackageDialog(this, new CallBack() {
			@Override
			public void btnOk(Packages packages) {
				CookPromptlyActivity.this.packagesub = packages;
				CookPromptlyActivity.this.tv_packages.setText(new StringBuilder(String
						.valueOf(CookPromptlyActivity.this.packagesub.getName())).append("/")
						.append(CookPromptlyActivity.this.packagesub.getPrice()).append("\u5143(")
						.append(CookPromptlyActivity.this.packagesub.getDescription()).append(")").toString());
				CookPromptlyActivity.this.ll_package_gone
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				CookPromptlyActivity.this.ll_package_visible.setVisibility(0);
				CookPromptlyActivity.this.dialogPackages.dismiss();
			}
		});
	}

	private Dialog showTime() {
		View view = LayoutInflater.from(this).inflate(R.layout.dialog_time, null);
		this.btn_ok = (TextView) view.findViewById(R.id.btn_ok);
		this.btn_ok.setOnClickListener(this);
		this.date = (WheelView) view.findViewById(R.id.date);
		this.date.setVisibleItems(BitmapCacheManagementTask.MESSAGE_CLOSE);
		this.date.setViewAdapter(new CountryAdapter(this));
		String[][] cities = (String[][]) Array.newInstance(String.class, new int[] {
				this.cookResult.getWork_day().size(), 7 });
		for (int i = 0; i < cities.length; i++) {
			cities[i] = this.cookResult.getWork_day().get(i).getHh();
		}
		this.hours = (WheelView) view.findViewById(R.id.hours);
		this.hours.setVisibleItems(BitmapCacheManagementTask.MESSAGE_CLOSE);
		this.hours.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				if (!CookPromptlyActivity.this.scrolling) {
					CookPromptlyActivity.this.mActiveCities[CookPromptlyActivity.this.mActiveCountry] = newValue;
				}
			}
		});
		this.date.addChangingListener(new AnonymousClass_7(cities));
		this.date.addScrollingListener(new AnonymousClass_8(cities));
		this.date.setCurrentItem(1);
		if (this.cookResult.getWork_day().size() == 1) {
			updateCities(this.hours, cities, 0);
		}
		this.date.setCurrentItem(0);
		view.setMinimumWidth((int) ((Utils.getScreenWidth(this)) * 0.9d));
		Dialog dialog = new Dialog(this, 2131361801);
		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		Window dialogWindow = dialog.getWindow();
		LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(17);
		lp.x = 0;
		lp.y = 0;
		dialogWindow.setAttributes(lp);
		return dialog;
	}

	private void updateCities(WheelView city, String[][] cities, int index) {
		this.mActiveCountry = index;
		ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter(this, cities[index]);
		adapter.setItemResource(R.layout.dialog_simple_date_item);
		adapter.setItemTextResource(R.id.date_ymd);
		adapter.setTextTypeface(Typeface.DEFAULT);
		city.setViewAdapter(adapter);
		city.setCurrentItem(this.mActiveCities[index]);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == this.addressRequestCode && resultCode == -1) {
			this.addresses = (Addresses) data.getExtras().getSerializable("address");
			setAddress(this.addresses);
		}
		if (requestCode == this.loginRequest && resultCode == -1) {
			initAddress();
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == 0) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				hideSoftInput(v.getWindowToken());
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	private boolean isShouldHideInput(View v, MotionEvent event) {
		if (v == null || !(v instanceof EditText)) {
			return false;
		}
		int[] l = new int[2];
		v.getLocationInWindow(l);
		int left = l[0];
		int top = l[1];
		return event.getX() <= (left) || event.getX() >= (left + v.getWidth()) || event.getY() <= (top)
				|| event.getY() >= (top + v.getHeight());
	}

	private void hideSoftInput(IBinder token) {
		if (token != null) {
			((InputMethodManager) getSystemService("input_method")).hideSoftInputFromWindow(token,
					BitmapCacheManagementTask.MESSAGE_FLUSH);
			if (this.et_desc.getText().toString().trim().length() == 0) {
				this.tv_desc.setVisibility(0);
			}
			this.et_desc.clearFocus();
		}
	}
}
